import * as OTPAuth from 'otpauth';
import crypto from 'crypto';

/**
 * 生成TOTP密钥
 */
export function generateTotpSecret() {
  return OTPAuth.Secret.fromBase32(
    crypto.randomBytes(20).toString('base64').replace(/[^A-Z2-7]/gi, '').substring(0, 32)
  );
}

/**
 * 创建TOTP实例
 */
export function createTotp(options = {}) {
  const {
    secret,
    issuer = '2FA Manager',
    label,
    algorithm = 'SHA1',
    digits = 6,
    period = 30,
  } = options;
  
  return new OTPAuth.TOTP({
    issuer,
    label,
    algorithm,
    digits,
    period,
    secret: typeof secret === 'string' 
      ? OTPAuth.Secret.fromBase32(secret)
      : secret,
  });
}

/**
 * 生成TOTP验证码
 */
export function generateTotpCode(secret, options = {}) {
  const totp = createTotp({ secret, ...options });
  return totp.generate();
}

/**
 * 验证TOTP验证码
 */
export function verifyTotpCode(token, secret, options = {}) {
  const totp = createTotp({ secret, ...options });
  
  // 允许前后1个时间窗口（共90秒）
  const window = options.window || 1;
  const delta = totp.validate({ token, window });
  
  return delta !== null;
}

/**
 * 生成TOTP URI（用于二维码）
 */
export function generateTotpUri(options = {}) {
  const {
    secret,
    issuer = '2FA Manager',
    accountName,
    algorithm = 'SHA1',
    digits = 6,
    period = 30,
  } = options;
  
  const totp = createTotp({
    secret,
    issuer,
    label: accountName,
    algorithm,
    digits,
    period,
  });
  
  return totp.toString();
}

/**
 * 解析TOTP URI
 */
export function parseTotpUri(uri) {
  try {
    const totp = OTPAuth.URI.parse(uri);
    
    return {
      type: totp.constructor.name.toLowerCase(), // totp or hotp
      issuer: totp.issuer,
      label: totp.label,
      secret: totp.secret.base32,
      algorithm: totp.algorithm,
      digits: totp.digits,
      period: totp.period,
    };
  } catch (error) {
    throw new Error('Invalid TOTP URI: ' + error.message);
  }
}

/**
 * 生成QR Code数据URL（用于前端显示）
 */
export async function generateQrCodeDataUrl(uri) {
  // 这个函数将在前端实现，这里只返回URI
  return uri;
}

/**
 * 获取当前时间窗口的剩余秒数
 */
export function getTimeRemaining(period = 30) {
  const now = Math.floor(Date.now() / 1000);
  return period - (now % period);
}

/**
 * 验证TOTP配置是否有效
 */
export function validateTotpConfig(config = {}) {
  const { algorithm, digits, period } = config;
  
  const validAlgorithms = ['SHA1', 'SHA256', 'SHA512'];
  const validDigits = [6, 7, 8];
  const validPeriods = [15, 30, 60];
  
  const errors = [];
  
  if (algorithm && !validAlgorithms.includes(algorithm)) {
    errors.push(`Invalid algorithm. Must be one of: ${validAlgorithms.join(', ')}`);
  }
  
  if (digits && !validDigits.includes(digits)) {
    errors.push(`Invalid digits. Must be one of: ${validDigits.join(', ')}`);
  }
  
  if (period && !validPeriods.includes(period)) {
    errors.push(`Invalid period. Must be one of: ${validPeriods.join(', ')}`);
  }
  
  return {
    valid: errors.length === 0,
    errors,
  };
}

/**
 * 生成备份码（用于用户的2FA备份）
 */
export function generateBackupCodes(count = 10) {
  return Array.from({ length: count }, () => {
    return crypto.randomBytes(4).toString('hex').toUpperCase();
  });
}


